<template>
  <!-- 用户模块，采用前端搜索和分页 -->
  <div class="gx-panel">
    <!-- 新增和修改弹层 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="(action === 'add' ? '新增' : '修改') + '图片'"
      :visible.sync="visible"
      width="430px"
      @closed="$refs.form.clearValidate()"
    >
      <!-- 表单 -->
      <el-form label-width="90px" :model="form" :rules="rules" ref="form">
        <el-form-item label="账户" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="nickname"
          :rules="{ required: action === 'add', message: '请输入密码！' }"
        >
          <el-input type="password" v-model="form.password" :placeholder="action==='edit'?'不修改则保持为空！' : ''"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="上传头像" prop="avatar">
          <el-input v-model="form.avatar">
            <el-upload
              slot="append"
              action="http://cloud.scnew.com.cn/api/user/upload"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-button icon="el-icon-upload2"></el-button>
            </el-upload>
          </el-input>
        </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio v-model="form.gender" :label="2">男</el-radio>
        <el-radio v-model="form.gender" :label="1">女</el-radio>
      </el-form-item>
      <el-form-item label="所属角色" prop="role">
        <el-select v-model="form.role" clearable>
          <el-option v-for="item in []" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="审核">
          <el-switch
            v-model="form.state"
            :active-value="2"
            :inactive-value="1"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <div class="heading">
      <h1>用户管理</h1>
      <el-breadcrumb>
        <el-breadcrumb-item to="/control">后台首页</el-breadcrumb-item>
        <el-breadcrumb-item to="/control/admin">用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="search">
      <el-form :inline="true">
        <el-form-item v-if="ids.length">
          <el-button type="danger" size="small" @click="handelRemove(ids)"
            >批量删除</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-select
            v-model.number="condition.state"
            placeholder="是否审核"
            clearable
            size="small"
            style="width: 100px"
          >
            <el-option label="未审核" value="1">未审核</el-option>
            <el-option label="未审核" value="2">已审核</el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="condition.keyword"
            placeholder="请输入账号 / 昵称 / 手机"
            clearable
            size="small"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-button type="danger" icon="el-icon-plus" size="small" @click="add"
        >增加</el-button
      >
    </div>
    <div class="grid">
      <el-table
        :data="pageData"
        style="witdh: 100%"
        @selection-change="handleSelectionChange"
        ref="table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="头像" v-slot="scope">
          <el-image
            style="height: 40px"
            :src="scope.row.avatar"
            fit="cover"
          ></el-image>
        </el-table-column>

        <el-table-column label="账号" prop="username" />
        <el-table-column label="昵称" prop="nickname" />
        <el-table-column label="手机" prop="mobile" />
        <el-table-column
          label="登录日期"
          prop="pubdate"
          :formatter="handleDate"
          sortable
        />
        <el-table-column label="审核" v-slot="scope" :width="110">
          <el-switch
            v-model="scope.row.state"
            :active-value="2"
            :inactive-value="1"
            @change="handleSwitchChange(scope.row)"
          />
        </el-table-column>
        <el-table-column label="操作" width="200" v-slot="scope">
          <template>
            <el-button size="mini" @click="edit(scope.row)">修改</el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handelRemove([scope.row.id])"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="gx-pagination"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="page"
        :page-sizes="[1, 2, 3]"
        :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchData.length"
      />
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { pick } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      action: 'add',
      condition: {},
      listData: [],
      form: {},
      rules: {
        username: { required: true, message: '请输入账号' },
        nickname: { required: true, message: '请上传昵称' },
        mobile: { required: true, message: '请输入手机号' }
      },
      // 复选框选中的id值
      ids: [],
      // 分页信息 pageSize每页分多少条
      page: 1,
      pageSize: 1
    }
  },
  computed: {
    searchData () {
      const { state, keyword } = this.condition
      return this.listData.filter((item) => {
        return (
          (state ? item.state === state : true) &&
          (keyword
            ? item.username.includes(keyword) ||
              item.nickname.includes(keyword) ||
              item.mobile.includes(keyword)
            : true)
        )
      })
    },
    pageData () {
      const start = (this.page - 1) * this.pageSize
      const end = start + this.pageSize
      return this.searchData.slice(start, end)
    }
  },
  created () {
    this.query()
  },
  methods: {
    query () {
      this.$http.get('admin/list').then((res) => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        } else {
          this.listData = res.result
        }
      })
    },
    handleDate (row) {
      return moment(row.pubdate).format('YYYY年MM月DD日')
    },
    handleSelectionChange (arr) {
      this.ids = arr.map((item) => item.id)
    },
    handleCurrentChange (page) {
      this.page = page
    },
    handleSizeChange (size) {
      this.pageSize = size
    },
    handleSwitchChange ({ id, state }) {
      this.$http.post('admin/state', { id, state }).then((res) => {
        if (res.err > 0) {
          this.$message.error(res.desc)
        }
      })
    },
    handelRemove (ids) {
      this.$confirm('你确定删除所选相互据吗?', '提示')
        .then(() => {
          this.$http.post('admin/remove', { ids }).then((res) => {
            if (res.err > 0) {
              this.$message.error(res.desc)
            } else {
              this.query()
            }
          })
        })
        .catch(() => {
          // 调用table组件的methods方法  clearSelection清除选择(按取消的时候取消全选)
          this.$refs.table.clearSelection()
        })
    },
    add () {
      this.visible = true
      this.action = 'add'
      this.form = { state: 2 }
    },
    edit (row) {
      this.visible = true
      this.action = 'edit'
      this.form = pick(row, ['id', 'username', 'nickname', 'mobile', 'avatar', 'gender', 'role', 'state'])
    },
    save () {
      this.$refs.form.validate((vaild) => {
        if (vaild) {
          this.$http.post(`admin/${this.action}`, this.form).then((res) => {
            if (res.err > 0) {
              this.$message.error(res.desc)
            } else {
              this.query()
              this.$message.success(res.desc)
              this.visible = false
            }
          })
        }
      })
    },
    beforeUpload (file) {
      const ext = file.name.match(/\.(\w+)$/i)[1].toLowerCase()
      const isPic = ['jpeg', 'png', 'gif', 'jpg', 'webp']
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic.includes(ext)) { this.$message.error('上传图片只能是 ' + isPic + ' 格式!') }
      if (!isLt2M) this.$message.error('上传图片大小不能超过 2MB!')
      return isPic && isLt2M
    },
    uploadSuccess (res) {
      if (res.err > 0) {
        this.$message.error(res.desc)
      } else {
        this.$message.success(res.desc)
        this.$set(this.form, 'avatar', res.result)
      }
    }
  }
}
</script>

<style scoped>
</style>
